import {Router} from 'express';
import User from '../models/user';


const router= Router();


/*设置路由*/
export const prefix='/account';


router.get('/login', (req, res) => {
    res.render('account/login', { user: {}, message: '' })
})



/*登录*/
router.post('/login', function (req, res) {
    User.getByUsername(req.body.username)
        .then(user=>{
            console.log(user);
            if(!user){
                //用户名或密码错误
                return res.send('用户名或密码错误');
            }
            if(user.password != req.body.password){
                return res.send('用户名或密码错误');
            }
            res.send('登录成功');
        })
        .catch(error=>{
             throw error;
        })

});


router.post('/register', function (req, res) {
    /*1.接收客户资料*/
    /*2.验证合法效验*/
    if(!req.body.rememberme){
        return res.render('account/login',{user:req.body,message:'你必须同意'});

    }
    if(req.body.confirm!= req.body.Password){
        return res.send('两次密码不正确');
    }

    //判断是否存在
   User.existUsername(req.body.username)
       .then(exist=>{
           if(exist){
               res.send('用户名已经存在');
           }else{
               const  user = new User(Math.random()*10,req.body.username,req.body.Password,'',req.body.email,'1',new Date());
               return user.save()

           }
       })
       .then(u=>{
           if(u){
               res.send('注册成功');
           }
       })
       .catch(
           error=>{
               throw error
           }
       )
});



export default router;